package cn.ss.exam2302.service.impl;

import cn.ss.exam2302.entity.JsonResult;
import cn.ss.exam2302.entity.User;
import cn.ss.exam2302.mapper.UserMapper;
import cn.ss.exam2302.service.UserService;
import cn.ss.exam2302.util.EncryptUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    String usrSalt = "9a75f9707d243d7949bb61594aa82e27";

    @Override
    public User selectOneByAccount(String account) {
        return null;
    }

    @Override
    @Transactional(readOnly = true)
    public User queryOneByAccount(String account) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("usr_account", account);
        return userMapper.selectOne(userQueryWrapper);
    }

    @Override
    public JsonResult insert(User user) {
        String usrPassword = EncryptUtil.generatePassword(user.getUsrPassword(), usrSalt);
        userMapper.insert(new User(user.getUsrName(), user.getUsrAccount(), usrPassword, usrSalt, user.getUsrRole(), null, new Date(), new Date()));
        return JsonResult.JSONRESULT_SUCCESS;
    }

    @Override
    @Transactional(readOnly = true)
    public List<User> queryALl() {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.ne("usr_role", "SYSTEM");
        return userMapper.selectList(userQueryWrapper);
    }

    @Override
    public JsonResult resetPassword(String password, String usrAccount) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("usr_account", usrAccount);
        User user = userMapper.selectOne(userQueryWrapper);
        String usrPassword = EncryptUtil.generatePassword(password, usrSalt);
        user.setUsrPassword(usrPassword);
        user.setUsrUpdatedate(new Date());
        userMapper.updateById(user);
        return JsonResult.JSONRESULT_SUCCESS;
    }

    @Override
    public JsonResult delete(String status, String usrAccount) {
        Boolean usrDelete = status.equals("正常") ? true : null;
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("usr_account", usrAccount);
        User user = userMapper.selectOne(userQueryWrapper);
        user.setUsrDelete(usrDelete);
        user.setUsrUpdatedate(new Date());
        userMapper.updateById(user);
        return JsonResult.JSONRESULT_SUCCESS;
    }
}
